package com.itfenghuang.service.imp;

import com.itfenghuang.bean.Student;
import com.itfenghuang.mapper.StudentMapper;
import com.itfenghuang.service.StudentService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class StudentServiceImp implements StudentService {
    @Override
    public List<Student> selectStudent() {
        InputStream is=null;
        SqlSession sqlSession=null;
        List<Student> list=null;
        try {
            //1.加载核心配置文件
            is = Resources.getResourceAsStream("MyBatisConfig.xml");
            // 2).获取SqlSession工厂对象
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
            //3.获取SqlSession对象
            sqlSession = factory.openSession();
            //4).通过SqlSession对象获取StudentMapper接口的实现类对象
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
            //5.通过对象调用对应的增删改查方法
            list = mapper.selectStudent();
            //6处理结果
            for (Student stu : list) {
                System.out.println(stu);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (sqlSession!=null){
                sqlSession.close();
            }
            if (is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
